package cool.mylog.mylog2end.bean;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.Fastjson2TypeHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Log表实体类
 */
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "log", autoResultMap = true)
public class Log {
    @TableId
    private Long id;

    private Long userid;

    private String username;

    private String type;

    private Date sendtime; // 发送时间

    private Date logtime; // 记录时间

    private String content;

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray tags = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray imgs = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray videos = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray audios = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray files = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray location = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONArray people = new JSONArray();

    @TableField(typeHandler = Fastjson2TypeHandler.class)
    private JSONObject info = new JSONObject();

    /**
     * 根据JSON字符串生成Log对象
     * JSON中没有的既设置为null
     *
     * @return Log对象
     */
    public static Log getLogByJson(String logJson) {
        JSONObject logJsonObj = JSON.parseObject(logJson);
        return new Log(
                logJsonObj.getLong("id"),
                logJsonObj.getLong("userid"),
                logJsonObj.getString("username"),
                logJsonObj.getString("type"),
                logJsonObj.getDate("sendtime"),
                logJsonObj.getDate("logtime"),
                logJsonObj.getString("content"),
                logJsonObj.getJSONArray("tags"),
                logJsonObj.getJSONArray("imgs"),
                logJsonObj.getJSONArray("videos"),
                logJsonObj.getJSONArray("audios"),
                logJsonObj.getJSONArray("files"),
                logJsonObj.getJSONArray("location"),
                logJsonObj.getJSONArray("people"),
                logJsonObj.getJSONObject("info")
        );
    }
}
